package nccloud.mob.riart.message.actions;

import java.util.Map;

import com.alibaba.fastjson.JSONObject;

import nc.bs.logging.Logger;
import nc.bs.pf.pub.PfDataCache;
import nc.itf.pub.workflowqry.IFlowInstanceQuery;
import nc.itf.uap.busibean.ISysInitQry;
import nc.itf.uap.pf.IPFWorkflowQry;
import nc.itf.uap.pf.IWorkflowDefine;
import nc.jdbc.framework.exception.DbException;
import nc.vo.ml.NCLangRes4VoTransl;
import nc.vo.pub.BusinessException;
import nc.vo.pub.para.SysInitVO;
import nc.vo.pub.pf.IWorkFlowStatus;
import nc.vo.pub.workflowqry.FlowHistoryQryResult;
import nc.vo.uap.wfmonitor.ProcessRouteRes;
import nc.vo.wfengine.core.parser.XPDLParserException;
import nc.vo.wfengine.core.workflow.BasicWorkflowProcess;
import nc.vo.wfengine.definition.WorkflowDefinitionVO;
import nc.vo.wfengine.definition.WorkflowTypeEnum;
import nccloud.baseapp.core.log.NCCForUAPLogger;
import nccloud.framework.core.exception.ExceptionUtils;
import nccloud.framework.mob.action.itf.IMobileAction;
import nccloud.framework.mob.container.IMobRequest;
import nccloud.framework.service.ServiceLocator;
import nccloud.utils.riart.MessageLogger;
import nccloud.vo.pf.flowinstance.NCCFlowInstanceVO;
import uap.apppf.util.SQLTransferMeaningUtil;

public class FlowStateQueryAction implements IMobileAction {

	@Override
	public Object doAction(IMobRequest request) {
		String billType = "";
		String billId = "";
		JSONObject json = new JSONObject();
		String jsonStr = request.read();
		JSONObject json2 = JSONObject.parseObject(jsonStr);
		billType = json2.get("billtype").toString();
		billId = json2.get("billid").toString();
		NCCFlowInstanceVO flowInstnceVO = null;

		//
		String flowState = "";
		try {
			NCCFlowInstanceVO[] vos = ServiceLocator
					.find(IFlowInstanceQuery.class)
					.findFlowInstancesByBillIdAndBillTypeAppendOrderByCondition(
							billId, billType);
			if (vos != null && vos.length > 0) {
				flowInstnceVO = vos[0];
				billId = flowInstnceVO.getBillversionpk();
			} else {

				json.put(
						"flowState",
						nc.vo.ml.NCLangRes4VoTransl.getNCLangRes().getStrByID(
								"0020nccloud_0", "0ncc0020001-0440")/* @res 无审批流 */);
				json.put("flowcode", null);
				return json;

			}

			FlowHistoryQryResult result = ServiceLocator.find(
					IPFWorkflowQry.class).queryFlowHistoryQryResult(billType,
					billId, Integer.valueOf(flowInstnceVO.getWorkflow_type()));

			ProcessRouteRes processRoute = result.getProcessRoute();
			String strWhere = null;
			strWhere = getModuleSQLPiece("1018") + " AND "
					+ " showflag ='Y' AND pk_org = 'GLOBLE00000000000000' ";

			String condition = " pub_sysinit.INITCODE = 'flow_forecast'";
			String strOrder = " groupcode, pub_sysinittemp.initcode";
			if (condition != null)
				strWhere = strWhere + " AND " + condition;
			SysInitVO[] sysInitVOs = null;
			ISysInitQry iSysInitQry = (ISysInitQry) ServiceLocator
					.find(ISysInitQry.class);
			try {
				sysInitVOs = iSysInitQry.getSysInitVOsFromJoinTable(strWhere,
						strOrder);
			} catch (BusinessException e1) {
				MessageLogger.error("操作此类【nccloud.mob.riart.message.actions.FlowStateQueryAction】是出现错误，错误描述：【"+e1.getMessage()+"】");
				Logger.error(e1.getMessage(), e1);
			}

			boolean isforecast = false;
			if (sysInitVOs != null && sysInitVOs[0] != null
					&& sysInitVOs[0].getValue() != null) {
				if (Integer.valueOf(flowInstnceVO.getWorkflow_type()) == WorkflowTypeEnum.Approveflow
						.getIntValue()) {
					isforecast = "Y".equals(sysInitVOs[0].getValue()) ? true
							: false;
				}
			}

			json.put("isforecast", isforecast);

			findAllWps(json, processRoute.getProcessDefPK());

			int state = ServiceLocator.find(IPFWorkflowQry.class)
					.queryFlowStatus(billType, billId,
							Integer.valueOf(flowInstnceVO.getWorkflow_type()));

			if (Integer.valueOf(flowInstnceVO.getWorkflow_type()) == WorkflowTypeEnum.Approveflow
					.getIntValue()) {

				switch (state) {
				case IWorkFlowStatus.WORKFLOW_FINISHED:
					flowState = NCLangRes4VoTransl.getNCLangRes().getStrByID(
							"pfworkflow", "UPPpfworkflow-000273")/* @res "审批通过" */;
					break;

				case IWorkFlowStatus.WORKFLOW_ON_PROCESS:
					flowState = NCLangRes4VoTransl.getNCLangRes().getStrByID(
							"pfworkflow", "UPPpfworkflow-000502")/* @res "审批进行中" */;
					break;

				case IWorkFlowStatus.NOT_STARTED_IN_WORKFLOW:
					flowState = NCLangRes4VoTransl.getNCLangRes().getStrByID(
							"pfworkflow", "UPPpfworkflow-000503")/* @res "提交态" */;
					break;

				case IWorkFlowStatus.NOT_APPROVED_IN_WORKFLOW:
					flowState = NCLangRes4VoTransl.getNCLangRes().getStrByID(
							"pfworkflow", "UPPpfworkflow-000274")/* @res "审批不通过" */;
					break;

				case IWorkFlowStatus.BILLTYPE_NO_WORKFLOW:
					flowState = NCLangRes4VoTransl.getNCLangRes().getStrByID(
							"pfworkflow", "UPPpfworkflow-000504")/* @res "无审批流" */;

					break;
				case IWorkFlowStatus.BILL_NOT_IN_WORKFLOW:
					flowState = NCLangRes4VoTransl.getNCLangRes().getStrByID(
							"pfworkflow", "UPPpfworkflow-000504")/* @res "无审批流" */;

					break;
				default:
					break;
				}

			} else if (Integer.valueOf(flowInstnceVO.getWorkflow_type()) == WorkflowTypeEnum.Workflow
					.getIntValue()) {

				switch (state) {
				case IWorkFlowStatus.WORKFLOW_FINISHED:
					flowState = NCLangRes4VoTransl.getNCLangRes().getStrByID(
							"pfworkflow", "UPPpfworkflow-000017")/* 工作流结束 */;
					break;
				case IWorkFlowStatus.WORKFLOW_ON_PROCESS:
					flowState = NCLangRes4VoTransl.getNCLangRes().getStrByID(
							"pfworkflow", "UPPpfworkflow-000018")/* 工作流进行中 */;
					break;

				case IWorkFlowStatus.NOT_STARTED_IN_WORKFLOW:
					flowState = NCLangRes4VoTransl.getNCLangRes().getStrByID(
							"pfworkflow", "UPPpfworkflow-000019")/* 工作流已启动 */;
					break;

				case IWorkFlowStatus.NOT_APPROVED_IN_WORKFLOW:
					flowState = NCLangRes4VoTransl.getNCLangRes().getStrByID(
							"pfworkflow", "UPPpfworkflow-000274")/* @res "审批不通过" */; // 工作流中没有这个状态
					break;

				case IWorkFlowStatus.BILLTYPE_NO_WORKFLOW:
					flowState = NCLangRes4VoTransl.getNCLangRes().getStrByID(
							"pfworkflow", "UPPpfworkflow-000020")/* 无工作流 */;
					break;
				case IWorkFlowStatus.BILL_NOT_IN_WORKFLOW:
					flowState = NCLangRes4VoTransl.getNCLangRes().getStrByID(
							"pfworkflow", "UPPpfworkflow-000020")/* 无工作流 */;
					break;
				default:
					break;
				}

			}

			json.put("flowState", flowState);
			if (Integer.valueOf(flowInstnceVO.getWorkflow_type()).intValue() == WorkflowTypeEnum.Approveflow
					.getIntValue()
					|| Integer.valueOf(flowInstnceVO.getWorkflow_type())
							.intValue() == WorkflowTypeEnum.SubApproveflow
							.getIntValue()) {

				json.put("flowcode", 2);
			} else {
				json.put("flowcode",
						Integer.valueOf(flowInstnceVO.getWorkflow_type())
								.intValue());
			}
			return json;

		} catch (BusinessException e) {
			MessageLogger.error("操作此类【nccloud.mob.riart.message.actions.FlowStateQueryAction】是出现错误，错误描述：【"+e.getMessage()+"】");
			ExceptionUtils.wrapException(e);
		}catch(Exception  e) {
			MessageLogger.error("操作此类【nccloud.mob.riart.message.actions.FlowStateQueryAction】是出现错误，错误描述：【"+e.getMessage()+"】");
		}

		return nc.vo.ml.NCLangRes4VoTransl.getNCLangRes().getStrByID(
				"0020nccloud_0", "0ncc0020001-0441")/* @res 自由态 */;

	}

	private void findAllWps(Map allwps, String defpk) throws BusinessException {
		WorkflowDefinitionVO[] wps = null;
		try {
			wps = ServiceLocator.find(IWorkflowDefine.class)
					.findSubWorkflowDefByParentPK(defpk);
		} catch (DbException e) {
			NCCForUAPLogger.error(e.getMessage(), e);
			ExceptionUtils.wrapException(e);
		} catch (BusinessException e) {
			// TODO Auto-generated catch block
			ExceptionUtils.wrapException(e);
		}

		WorkflowDefinitionVO[] vos = ServiceLocator.find(IWorkflowDefine.class)
				.queryWFDefWithoutContentVOs(new String[] { defpk });
		if (vos[0].getWorkflow_type() == WorkflowTypeEnum.Approveflow
				.getIntValue()
				|| vos[0].getWorkflow_type() == WorkflowTypeEnum.Workflow
						.getIntValue()) {

			allwps.put("main", vos[0].getNode_name() + vos[0].getVersion()/*
																		 * mainworkflow
																		 * .
																		 * getVersion
																		 * ()
																		 */);
		}

		if (wps != null && wps.length > 0) {
			for (WorkflowDefinitionVO vo : wps) {

				BasicWorkflowProcess subworkflow = null;
				try {
					subworkflow = PfDataCache.getWorkflowProcess(vo
							.getPrimaryKey());
				} catch (XPDLParserException e) {
					Logger.error(e);
				} catch (BusinessException e) {
					Logger.error(e);
				}
				allwps.put(subworkflow.findStartActivity().getId(),
						vo.getNode_name() + vo.getVersion());
				findAllWps(allwps, vo.getPk_wf_def());
			}

		} else {
			return;
		}
	}

	private String getModuleSQLPiece(String module) {
		if ("root".equals(module))
			return " 1=1 ";
		String whereSql = " and ((domainflag  not in (select fromid from pub_appcategory_child where"
				+ " fromtype ='Moduleid'and fromid<>'"
				+ module
				+ "') and apptag is null) or"
				+ " (apptag  not in (select fromid from pub_appcategory_child where   fromtype ='Apptag')"
				+ " and apptag is not null))";
		if (module.length() == 2)
			return " domainflag LIKE '" + SQLTransferMeaningUtil.tmsql(module)
					+ "%'" + whereSql;

		return " domainflag = '" + SQLTransferMeaningUtil.tmsql(module) + "'"
				+ whereSql;
	}

}
